package top.mcwebsite.lib.serviceManager.plugin

import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.commons.AdviceAdapter

class ServiceProviderInjectMethodVisitor(
    methodVisitor: MethodVisitor,
    private val serviceProviders: Set<String>,
    access: Int,
    name: String?,
    descriptor: String?
) : AdviceAdapter(Opcodes.ASM9, methodVisitor, access, name, descriptor) {
    override fun onMethodEnter() {
        serviceProviders.forEach { className ->
            mv.visitFieldInsn(
                Opcodes.GETSTATIC,
                "top/mcwebsite/playandroid/lib/servicemanager/core/ServiceManager",
                "INSTANCE",
                "Ltop/mcwebsite/playandroid/lib/servicemanager/core/ServiceManager;"
            )
            // 创建 ServiceProvider 对象
            mv.visitTypeInsn(Opcodes.NEW, className)
            mv.visitInsn(Opcodes.DUP) // 复制 Foo 实例引用
            mv.visitMethodInsn(
                Opcodes.INVOKESPECIAL,
                className,
                "<init>",
                "()V",
                false
            )
            // 调用注册的方法 top.mcwebsite.playandroid.lib.servicemanager.core.IServiceProvider
            mv.visitMethodInsn(
                Opcodes.INVOKEVIRTUAL,
                "top/mcwebsite/playandroid/lib/servicemanager/core/ServiceManager",
                "registerServiceByServiceProvider",
                "(Ltop/mcwebsite/playandroid/lib/servicemanager/core/IServiceProvider;)V",
                false
            )
        }
        super.onMethodEnter()
    }
}